<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div style="margin-bottom: 10px;">
        <!-- 表单 -->
        <el-dialog title="提示" :close-on-click-modal="false" :visible.sync="visible" width="500px" @close="handlerCancel">
          <el-form ref="formRef" :model="form" size="small" label-width="120px">
            <el-form-item label="点位">
              <el-select v-model="form.point" style="width: 250px;" placeholder="请选择">
                <el-option
                  v-for="(item, index) in pointList"
                  :key="index"
                  :label="item.descript"
                  :value="item.pointCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handlerCancel">取 消</el-button>
            <el-button type="primary" @click="handlerConfirm">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div>
        <label class="el-form-item-label" style="font-size: 20px">
          刷新间隔(秒/s):</label>
        <el-input
          v-model="interval"
          type="number"
          placeholder="请输入"
          class="filter-item"
          style="width: 100px;"
          @change="searchMaterialBard"
        />
        <!-- 搜索 -->
        <label class="el-form-item-label">立库搬运任务id</label>
        <el-input v-model="query.wmsTaskId" clearable placeholder="立库搬运任务id" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">轨道车搬运任务id</label>
        <el-input v-model="query.agvTaskId" clearable placeholder="轨道车搬运任务id" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">载盘码</label>
        <el-input v-model="query.palletCode" clearable placeholder="载盘码" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">任务类型</label>
        <!-- <el-input v-model="query.orderType" clearable placeholder="配送单类型 1离库, 2 回库, 3缓存区至产线" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <el-select v-model="query.orderType" class="filter-item" style="width: 160px;" filterable placeholder="请选择类型" @change="crud.toQuery">
          <el-option
            v-for="item in dict.delivery_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">任务状态</label>
        <el-select v-model="query.status" class="filter-item" style="width: 160px;" filterable placeholder="请选择状态" @change="crud.toQuery">
          <el-option
            v-for="item in dict.delivery_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- <el-input v-model="query.status" clearable placeholder="0待执行, 1开始执行, 2一段运行中,3 一段完成, 4二段运行中, 5完成" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <rrOperation :crud="crud" />
        <el-button
          v-if="crud.optShow.download"
          :loading="crud.downloadLoading"
          :disabled="!crud.data.length"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-download"
          @click="crud.doExport"
        >导出</el-button>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!-- <crudOperation :permission="permission" /> -->
      <div>
        <label class="el-form-item-label">选择起点类型</label>
        <el-select v-model="createForm.fromType" clearable class="filter-item" style="width: 160px;" filterable placeholder="请选择类型" @change="getFromTo('from', $event)">
          <el-option
            v-for="item in fromTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- <el-select v-model="query.from" class="filter-item" style="width: 160px;" filterable placeholder="请选择起点">
          <el-option
            v-for="item in fromList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <label class="el-form-item-label">选择终点类型</label>
        <el-select v-model="createForm.toType" clearable class="filter-item" style="width: 160px;" filterable placeholder="请选择类型" @change="getFromTo('to', $event)">
          <el-option
            v-for="item in toTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- <el-select v-model="query.to" class="filter-item" style="width: 160px;" filterable placeholder="请选择终点">
          <el-option
            v-for="item in toList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-button type="primary" size="mini" class="filter-item" :disabled="fromList.length === 0 || toList.length === 0" @click="createMission">创建任务</el-button>
      </div>
      <el-dialog title="创建配送单" :close-on-click-modal="false" :visible.sync="dialog" width="500px" @close="missionCancel">
        <el-form ref="formRef" :model="createForm" size="small" label-width="120px">
          <el-form-item label="选择起点">
            <el-select v-model="createForm.from" style="width: 200px;" filterable placeholder="请选择起点" @change="checkStatus('from', $event)">
              <el-option
                v-for="item in fromList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-tag
              size="medium"
              :type="fromStatus != null ? (fromStatus === 1 ? 'success' : 'danger') : 'info'"
            >
              {{ fromStatus != null ? (fromStatus === 1 ? '有货' : '无货') : '未知' }}
            </el-tag>
          </el-form-item>
          <el-form-item label="选择终点">
            <el-select v-model="createForm.to" style="width: 200px;" filterable placeholder="请选择终点" @change="checkStatus('to', $event)">
              <el-option
                v-for="item in toList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-tag
              size="medium"
              :type="toStatus !== null ? (toStatus === 1 ? 'success' : 'danger') : 'info'"
            >
              {{ toStatus !== null ? (toStatus === 1 ? '有货' : '无货') : '未知' }}
            </el-tag>
          </el-form-item>
        </el-form>
        <el-alert
          v-if="!(fromStatus === 1 && toStatus === 0) && (fromStatus !== null && toStatus !== null)"
          title="请确认取货位置是否有货和放货位置是否无货"
          type="error"
          show-icon
          center
          :closable="false"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="missionCancel">取 消</el-button>
          <el-button
            type="primary"
            :disabled="fromStatus === null || toStatus === null"
            :loading="btn.confirmCreate"
            @click="confirmCreate"
          >确 定</el-button>
        </div>
      </el-dialog>
      <!--表单组件-->
      <!-- <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="35%">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="auto">
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog> -->
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="agvTaskId" label="轨道车搬运任务id" />
        <el-table-column prop="palletCode" label="载盘码" />
        <el-table-column prop="fromLocation" label="起点" />
        <el-table-column prop="toLocation" label="终点" />
        <el-table-column prop="orderType" label="配送单类型">
          <template slot-scope="scope">
            {{ dict.label.delivery_type[scope.row.orderType] }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="任务状态">
          <template slot-scope="scope">
            {{ dict.label.delivery_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','deliveryOrder:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <!-- <udOperation
              :data="scope.row"
              :permission="permission"
            /> -->
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="点击此按钮,将强制结束该任务,是否继续"
              @confirm="forceComplete(scope.row, scope.$index)"
            >
              <el-button slot="reference" size="mini" type="danger" icon="el-icon-switch-button" :loading="btn.forceEnd === scope.$index">强制结束</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { getListAPI, getPointAPI, createMissionAPI, getFormToAPI, checkStatusAPI, newCreateMissionAPI } from '@/api/createDeliveryOrder'
import crudDeliveryOrder from '@/api/deliveryOrder'
import { forceEndAPI } from '@/api/createDeliveryOrder'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
// import crudOperation from '@crud/CRUD.operation'
// import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, wmsTaskId: null, agvTaskId: null, palletCode: null, orderType: null, status: null }
export default {
  name: 'DeliveryOrder',
  components: { pagination, rrOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['delivery_status', 'delivery_type'],
  cruds() {
    return CRUD({ title: '配送单', url: 'api/deliveryOrder', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDeliveryOrder },
      optShow: {
        edit: false,
        download: true,
        reset: true,
        add: false,
        del: false
      }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'deliveryOrder:add'],
        edit: ['admin', 'deliveryOrder:edit'],
        del: ['admin', 'deliveryOrder:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'wmsTaskId', display_name: '立库搬运任务id' },
        { key: 'agvTaskId', display_name: '轨道车搬运任务id' },
        { key: 'palletCode', display_name: '载盘码' },
        { key: 'orderType', display_name: '配送单类型 1离库, 2 回库, 3缓存区至产线' },
        { key: 'status', display_name: '0待执行, 1开始执行, 2一段运行中,3 一段完成, 4二段运行中, 5完成' }
      ],
      btn: {
        forceEnd: '',
        loading: ''
      },
      boxList: [
      ],
      visible: false,
      pointList: [],
      form: {
        point: ''
      },
      currentCode: '',
      // intervalId: null,
      // interval: localStorage.getItem('interval') || 5,
      fromList: [],
      toList: [],
      fromTypeList: [{
        value: 3,
        label: '缓存架'
      }, {
        value: 4,
        label: '叠合台'
      }, {
        value: 1,
        label: '升降台'
      }],
      toTypeList: [{
        value: 3,
        label: '缓存架'
      }, {
        value: 4,
        label: '叠合台'
      }, {
        value: 1,
        label: '升降台'
      }],
      createForm: {
        fromType: null,
        toType: null,
        from: null,
        to: null
      },
      dialog: false,
      fromStatus: null,
      toStatus: null,
      intervalId: null,
      interval: localStorage.getItem('interval') || 5
    }
  },
  mounted() {
    if (this.interval) {
      this.searchMaterialBard()
    }
  },
  destroyed() {
    this.clearTimer()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    searchMaterialBard() {
      // console.log(this.interval)
      localStorage.setItem('interval', this.interval)
      this.clearTimer()
      this.crud.toQuery()
      this.startTimer()
    },
    startTimer() {
      this.intervalId = setInterval(() => {
        this.crud.toQuery()
      }, this.interval * 1000) // 每1000毫秒（1秒）执行一次
    },
    async checkStatus(val, e) {
      const res = await checkStatusAPI(e)
      if (res.meta.code === 0) {
        switch (val) {
          case 'from':
            this.fromStatus = res.data.result
            break
          case 'to':
            this.toStatus = res.data.result
            break
        }
      }
    },
    missionCancel() {
      this.dialog = false
      this.fromStatus = null
      this.toStatus = null
      this.fromList = []
      this.toList = []
      this.createForm = {
        fromType: null,
        toType: null,
        from: null,
        to: null
      }
    },
    async confirmCreate() {
      const submitForm = {
        startLocation: this.fromList.find(item => item.value === this.createForm.from).label,
        endLocation: this.toList.find(item => item.value === this.createForm.to).label
      }
      try {
        this.btn.confirmCreate = true
        const res = await newCreateMissionAPI(submitForm)
        if (res.meta.code === 200) {
          this.$message.success('创建配送单成功')
          this.missionCancel()
          this.crud.toQuery()
        } else {
          this.$message.warning(res.meta.msg)
        }
      } finally {
        this.btn.confirmCreate = false
      }
    },
    createMission() {
      this.dialog = true
    },
    async getFromTo(val, e) {
      if (!e) return
      const submitForm = {
        pointDirection: val === 'from' ? 1 : 2,
        pointType: val === 'from' ? this.createForm.fromType : this.createForm.toType
      }
      const res = await getFormToAPI(submitForm)
      if (res.meta.code === 200) {
        switch (val) {
          case 'from':
            this.fromList = res.data.data.map(item => {
              const key = Object.keys(item)[0]
              return {
                label: item[key],
                value: key
              }
            })
            break
          case 'to':
            this.toList = res.data.data.map(item => {
              const key = Object.keys(item)[0]
              return {
                label: item[key],
                value: key
              }
            })
            break
        }
      } else {
        return this.$message.warning(res.meta.msg)
      }
    },
    clearTimer() {
      if (this.intervalId) {
        clearInterval(this.intervalId)
        this.intervalId = null
      }
    },
    async forceComplete(row, index) {
      try {
        this.btn.forceEnd = index
        const res = await forceEndAPI(row.id)
        if (res.meta.code === 200) {
          this.$message.success('强制结束成功')
          this.crud.toQuery()
        } else {
          this.$message.warning(res.meta.msg)
        }
      } finally {
        this.btn.forceEnd = ''
      }
    },
    async getList() {
      const res = await getListAPI()
      this.boxList = res.data.data
    },
    async outBoundConfirm(item) {
      this.currentCode = item.storageCode
      try {
        this.btn.loading = `${item.layer}/${item.column}`
        const res = await getPointAPI(item.storageCode)
        if (res.meta.code === 200) {
          this.pointList = res.data.data
          this.visible = true
        } else {
          this.$message.warning(res.meta.msg)
        }
      } finally {
        this.btn.loading = ''
      }
    },
    handlerCancel() {
      this.visible = false
      this.pointList = []
      this.form = {
        point: ''
      }
      this.currentCode = ''
    },
    async handlerConfirm() {
      const submitForm = {
        palletCode: this.currentCode,
        point: this.form.point,
        type: 1
      }
      const res = await createMissionAPI(submitForm)
      if (res.meta.code === 200) {
        this.$message.success('创建配送单成功')
        this.handlerCancel()
        // this.getList()
        this.crud.toQuery()
      } else {
        this.$message.warning(res.meta.msg)
      }
    }
  }
}
</script>

<style scoped>

</style>
